package com.unipay.system.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.unipay.common.result.Result;
import com.unipay.model.system.SysMenu;
import com.unipay.model.vo.AssginMenuVo;
import com.unipay.system.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author cmy
 * @since 2023-02-08
 */
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/admin/system/sysMenu")
public class SysMenuController {

    // 注入service
    @Autowired
    private SysMenuService sysMenuService;

    // TODO ---菜单：树形---
    @ApiOperation(value = "获取菜单列表")
    @GetMapping("/findNodes")
    public Result findNodes(){
        List<SysMenu> list = sysMenuService.findNodes();    // TODO 自定义实现
        return Result.ok(list);
    }

    @ApiOperation(value = "ID获取菜单")
    @GetMapping("/findNodeById/{id}")
    public Result findNodeById(@PathVariable("id") String id){
        SysMenu sysMenu = sysMenuService.getById(id);       // TODO SysMenuService extends IService<SysMenu>{}，因此方法直接调用，---无需“自定义”
        return Result.ok(sysMenu);
    }
    @ApiOperation(value = "新增菜单")
    @PostMapping("/save")
    public Result save(@RequestBody SysMenu permission) {
        boolean save = sysMenuService.save(permission);
        if (save){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    @ApiOperation(value = "修改菜单")
    @PutMapping("/update")
    public Result updateById(@RequestBody SysMenu permission) {
        boolean b = sysMenuService.updateById(permission);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    @ApiOperation(value = "删除菜单")
    @DeleteMapping("/remove/{id}")
    public Result removeById(@PathVariable Long id) {
        sysMenuService.removeById(id);
        return Result.ok();
    }
    @ApiOperation(value = "删除菜单（子菜单）")
    @DeleteMapping("/removeSub/{id}")
    public Result removeSub(@PathVariable Long id) {
        int i = sysMenuService.removeSubById(id);
        if (i > 0){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }


    /*
     *  TODO  给“角色”分配“菜单权限”
     * 1、进入分配页面：获取全部菜单及按钮，选中已选复选框，进行页面展示
     * 2、保存分配权限：删除之前分配的权限和保存现在分配的权限
     **/
    //（1）根据角色获取授权 “菜单权限” 数据
    @ApiOperation("根据角色获取菜单")
    @GetMapping("/toAssign/{roleId}")
    public Result toAssign(@PathVariable String roleId){
        List<SysMenu> menuList = sysMenuService.findSysMenuByRoleId(roleId);
        return Result.ok(menuList);
    }
    //（2）给角色分配 菜单权限
    @ApiOperation(value = "给角色分配权限")
    @PostMapping("/doAssign")
    public Result doAssign(@RequestBody AssginMenuVo assginMenuVo){
        sysMenuService.doAssign(assginMenuVo);
        return Result.ok();
    }
}

